#include "widget.h"
#include "ui_widget.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTcpSocket>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::handle);

    socket = new QTcpSocket(this);
    socket->connectToHost("127.0.0.1", 8080);
    bool ret = socket->waitForConnected();
    if(!ret)
    {
        QMessageBox::critical(this, "server conncet fail", "error occurs");
        exit(1);
    }

    connect(socket, &QTcpSocket::readyRead, this, [=](){
        QString message = socket->readAll();
        ui->listWidget->addItem("server says: " + message.toUtf8());
    });
}

void Widget::handle()
{
    QString message = ui->lineEdit->text();
    socket->write(message.toUtf8());
    ui->listWidget->addItem("client says: " + message);
    ui->lineEdit->clear();
}

Widget::~Widget()
{
    delete ui;
}
